const DB = require('../../../utils/db')
// 引入jwt token工具
const JwtUtil = require('../../../utils/jwt')
/**
 * GET
 * 根据id搜索群
 */
module.exports = async (ctx) => {
  let groupid = ctx.request.query.groupid
  // 获取token
  let token = ctx.request.header.authorization
  let jwt = new JwtUtil(token)
  // 用token获取到userid
  let userid = jwt.verifyToken()
  // 是否是群成员
  const isMember = await DB.query(
    `select * from user_group where (userid='${userid}' and groupid='${groupid}')`
  )
  console.log(
    isMember,
    'isMember',
    `select * from user_group where (userid='${userid}' and groupid='${groupid}')`
  )
  // group是关键字，查询群聊信息
  const groupInformation = await DB.query(
    `select groupName,introduction,lord,createTime from \`group\` where groupid='${groupid}'`
  )
  // 存在信息，表示有这个群聊
  if (groupInformation.length>0){
    if (isMember.length > 0) {
      // 已经是群成员了
      ctx.body = {
        code: 0,
        data: { ...groupInformation[0], isMember: true },
      }
    } else {
      // 不是群成员,那么查询申请信息
      const applyres = await DB.query(
        `select applyStatus from user_group_apply where userid='${userid}' and groupid='${groupid}'`
      )
      ctx.body = {
        code: 0,
        data: { ...groupInformation[0], isMember: false, ...applyres[0] },
      }
    }
  }else{
  ctx.body = {
    code: 0,
    data: null,
  }
  }

  

}
